package com.ficus.road.maintain.third.zh.maintenance;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ficus.road.maintain.core.model.zh.MileageStatistic;
import com.ficus.road.maintain.core.model.zh.MileageZH;
import com.ficus.road.maintain.dao.MileageInfoDao;
import com.ficus.road.maintain.util.MyDateUtil;
import com.ficus.road.maintain.third.zh.BaseZH;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author xiawen yang
 * @date 2022/4/1 下午3:14
 */
@Slf4j
@Component
public class ZHMileage extends BaseZH {

    @Autowired
    private MileageInfoDao mileageInfoDao;

    Pattern pattern = Pattern.compile("^(?!-|—).*[-—].*(?<!-|—)$");

    @PostConstruct
    void init() {
        arg0 = "ytYhMileageNum";
        arg1 = "{}";
        errMsg = "调用中海接口获取管养里程异常!";
        successMsg = "调用中海接口获取管养里程成功!";
    }

    /**
     * 修改数据库中原有的 错误道路起始点数据
     */
//    @PostConstruct
//    void correctDatabase() {
//        List<MileageStatistic> all = mileageInfoDao.findAll();
//        all.stream().forEach(mileageStatistic -> {
//            mileageStatistic.getDirect().getMileageList().forEach(mileageBridge -> {
//                mileageBridge.setStart(trimUnexpectedCharacter(pattern,mileageBridge.getStart()));
//                mileageBridge.setEnd(trimUnexpectedCharacter(pattern,mileageBridge.getEnd()));
////                if (mileageBridge == null)
////                    return;
////                String start = mileageBridge.getStart();
////                String end = mileageBridge.getEnd();
////                String start1 = trimUnexpectedCharacter(pattern, start);
////                String end1 = trimUnexpectedCharacter(pattern,end);
////                if (start!=start1 && !start.equals(start1)) {
////                    log.info("id = {} , roadId = {}, start = {},start1 = {},count = {}",mileageStatistic.getId(),mileageBridge.getRoadId(),start,start1);
////                }
////                if (end!=end1 && !end.equals(end1)) {
////                    log.info("id = {} , roadId = {}, end = {}, end1 = {}, count = {}",mileageStatistic.getId(),mileageBridge.getRoadId(),end,end1);
////                }
//            });
//            mileageStatistic.getRoad().getMileageList().forEach(mileageBridge -> {
//                mileageBridge.setStart(trimUnexpectedCharacter(pattern,mileageBridge.getStart()));
//                mileageBridge.setEnd(trimUnexpectedCharacter(pattern,mileageBridge.getEnd()));
////                if (mileageBridge == null)
////                    return;
////                String start = mileageBridge.getStart();
////                String end = mileageBridge.getEnd();
////                String start1 = trimUnexpectedCharacter(pattern, start);
////                String end1 = trimUnexpectedCharacter(pattern,end);
////                if (start != start1 && !start.equals(start1)) {
////                    log.info("id = {} , roadId = {}, start = {},start1 = {},count = {}",mileageStatistic.getId(),mileageBridge.getRoadId(),start,start1);
////                }
////                if (end != end1 && !end.equals(end1)) {
////                    log.info("id = {} , roadId = {}, end = {}, end1 = {}, count = {}",mileageStatistic.getId(),mileageBridge.getRoadId(),end,end1);
////                }
//            });
//            mileageInfoDao.saveOrUpdate(mileageStatistic);
//            log.info("刷新数据库覆盖旧道路起始点信息, id = {}",mileageStatistic.getId());
//        });
//        log.info("刷新数据库覆盖旧道路起始点信息完成...");
//    }

    //    @Scheduled(cron = "0/5 * * * * ?", zone = "GMT+8:00")
    @Scheduled(cron = "0 0 12,14,16 * * ?")
    public void refreshMileage() {
        String mileageStr = null;
        int i = 0;
        while (i < 10) {
            mileageStr = getZHData();
            if (ObjectUtils.isNotEmpty(mileageStr)) {
                break;
            }
            i++;
        }
        if (ObjectUtils.isEmpty(mileageStr)) {
            return;
        }
        MileageZH mileageZH = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            mileageZH = mapper.readValue(mileageStr, MileageZH.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String today = MyDateUtil.dateFormatStr(new Date(), "yyyy-MM-dd");
        MileageStatistic mileageStatistic = convert2MileageStatistic(mileageZH, today);
        mileageInfoDao.saveOrUpdate(mileageStatistic);
    }

    public MileageStatistic convert2MileageStatistic(MileageZH zh, String date) {
        MileageStatistic.TechStatistic techStatistic = MileageStatistic.TechStatistic.builder()
                .highway(Double.parseDouble(zh.getHighway()))
                .firstLevel(Double.parseDouble(zh.getFirstLevel()))
                .secondLevel(Double.parseDouble(zh.getSecondLevel()))
                .thirdLevel(Double.parseDouble(zh.getThirdLevel()))
                .build();
        MileageStatistic.AdministrativeStatistic administrativeStatistic = MileageStatistic.AdministrativeStatistic.builder()
                .state(Double.parseDouble(zh.getState()))
                .provincial(Double.parseDouble(zh.getProvincial()))
                .county(Double.parseDouble(zh.getCounty()))
                .build();
        List<MileageStatistic.MileageBridge> glsBridgeList = new ArrayList<>();
        zh.getRoadGls().forEach(item -> {
            String locationDesc = item.getLocationdesc();
            String[] split;
            String start = null;
            String end = null;
            if (ObjectUtils.isEmpty(locationDesc)) {
            } else if (locationDesc.contains("，")) {
                split = locationDesc.split("，");
                start = split[0];
                end = split[1];
            } else if (locationDesc.contains("--")) {
                split = locationDesc.split("--");
                start = split[0];
                end = split[1];
            }
            MileageStatistic.MileageBridge glsBridge = MileageStatistic.MileageBridge.builder()
                    .roadId(item.getRoadid())
                    .roadName(item.getRoadname())
                    .start(trimUnexpectedCharacter(pattern,start))
                    .end(trimUnexpectedCharacter(pattern,end))
                    .mileage(item.getMileage())
                    .company(item.getDepartname())
                    .build();
            glsBridgeList.add(glsBridge);
        });
        MileageStatistic.Direct direct = MileageStatistic.Direct.builder()
//                .annual(Integer.parseInt(zh.getHighwayMileage()))
//                .electronic(Integer.parseInt(zh.getHighwayElectronic()))
                .annual((int) Double.parseDouble(zh.getHighwayMileage()))
                .electronic((int) Double.parseDouble(zh.getHighwayElectronic()))
                .techStatistic(techStatistic)
                .administrativeStatistic(administrativeStatistic)
                .mileageList(glsBridgeList)
                .build();

        List<MileageStatistic.MileageBridge> cdBridgeList = new ArrayList<>();
        zh.getRoadCdzx().forEach(item -> {
            MileageStatistic.MileageBridge cdBridge = MileageStatistic.MileageBridge.builder()
                    .roadId(item.getRoadid())
                    .roadName(item.getRoadname())
                    .start(trimUnexpectedCharacter(pattern,item.getStartlocname()))
                    .end(trimUnexpectedCharacter(pattern,item.getEndlocname()))
                    .mileage(item.getMileage())
                    .company(item.getDepartname())
                    .build();
            cdBridgeList.add(cdBridge);
        });
        MileageStatistic.RoadTypeStatistic roadTypeStatistic = MileageStatistic.RoadTypeStatistic.builder()
                .freeway(Double.parseDouble(zh.getFreeway()))
                .mainRoad(Double.parseDouble(zh.getMainRoad()))
                .secondaryRoad(Double.parseDouble(zh.getSecondaryRoad()))
                .branchRoad(Double.parseDouble(zh.getBranchRoad()))
                .build();
        MileageStatistic.Road road = MileageStatistic.Road.builder()
//                .annual(Integer.parseInt(zh.getCityMileage()))
//                .electronic(Integer.parseInt(zh.getCityElectronic()))
                .annual((int) Double.parseDouble(zh.getCityMileage()))
                .electronic((int) Double.parseDouble(zh.getCityElectronic()))
                .roadTypeStatistic(roadTypeStatistic)
                .mileageList(cdBridgeList)
                .build();

        return MileageStatistic.builder()
                .id(date)
                .direct(direct)
                .road(road)
                .build();
    }

    /**
     * 删除道路起点终点名称前后的 - 和 () 等多余字符
     * @param location 道路起点 终点
     * @return
     */
    public String trimUnexpectedCharacter(Pattern pattern,String location) {
        if (location == null)
            return location;
        if (location.contains("(") && location.contains(")"))
            return location;
        if (location.contains("（") || location.contains("）"))
            return location;
        if (pattern.matcher(location.trim()).find())
            return location;
        return location.replaceAll("\\(|\\)|（|）|-|—","");
    }
}
